# 商品列表页面
<template>
  <div class="product-list-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="productList"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="商品分类" width="150" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            ¥{{ formatPrice(row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="sales" label="销量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                :type="row.status === 1 ? 'warning' : 'success'"
                link
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 1 ? '下架' : '上架' }}
              </el-button>
              <el-button
                type="primary"
                link
                @click="handleToggleRecommend(row)"
              >
                {{ row.isRecommend ? '取消推荐' : '推荐' }}
              </el-button>
              <el-button
                type="warning"
                link
                @click="handleToggleNew(row)"
              >
                {{ row.isNew ? '取消新品' : '新品' }}
              </el-button>
              <el-button
                type="success"
                link
                @click="handleToggleHot(row)"
              >
                {{ row.isHot ? '取消热销' : '热销' }}
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getMerchantProducts, 
  updateProductStatus,
  updateProductRecommendStatus,
  updateProductNewStatus,
  updateProductHotStatus
} from '@/api/admin'
import { getCategoryTree } from '@/api/category'

const route = useRoute()
const merchantId = computed(() => route.params.merchantId)

// 状态定义
const loading = ref(false)
const productList = ref([])
const categories = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = ref({
  name: '',
  categoryId: '',
  status: ''
})

// 获取商品列表
const fetchProducts = async () => {
  if (!merchantId.value) {
    ElMessage.warning('商家ID不能为空')
    return
  }

  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.value.name || undefined,
      categoryId: searchForm.value.categoryId || undefined,
      status: searchForm.value.status
    }
    
    // 移除值为undefined的参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await getMerchantProducts(merchantId.value, params)
    
    if (res?.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      productList.value = []
      total.value = 0
      ElMessage.warning(res?.message || '暂无商品数据')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
    productList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoryTree()
    if (res?.code === 200 && res.data) {
      categories.value = flattenCategoryTree(res.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
    categories.value = []
  }
}

// 将分类树扁平化为列表
const flattenCategoryTree = (tree) => {
  const result = []
  const flatten = (items, parentName = '') => {
    items.forEach(item => {
      const fullName = parentName ? `${parentName} / ${item.name}` : item.name
      result.push({
        id: item.id,
        name: fullName
      })
      if (item.children && item.children.length > 0) {
        flatten(item.children, fullName)
      }
    })
  }
  flatten(tree)
  return result
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchProducts()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    categoryId: '',
    status: ''
  }
  currentPage.value = 1
  fetchProducts()
}

// 切换商品状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const actionText = newStatus === 1 ? '上架' : '下架'
    
    await ElMessageBox.confirm(`确定要${actionText}该商品吗？`, '提示', {
      type: 'warning'
    })
    
    await updateProductStatus(row.id, newStatus === 1)
    ElMessage.success(`${actionText}成功`)
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 切换推荐状态
const handleToggleRecommend = async (row) => {
  try {
    const newStatus = !row.isRecommend
    const actionText = newStatus ? '推荐' : '取消推荐'
    
    await ElMessageBox.confirm(`确定要${actionText}该商品吗？`, '提示', {
      type: 'warning'
    })
    
    await updateProductRecommendStatus(row.id, newStatus)
    ElMessage.success(`${actionText}成功`)
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 切换新品状态
const handleToggleNew = async (row) => {
  try {
    const newStatus = !row.isNew
    const actionText = newStatus ? '设为新品' : '取消新品'
    
    await ElMessageBox.confirm(`确定要${actionText}该商品吗？`, '提示', {
      type: 'warning'
    })
    
    await updateProductNewStatus(row.id, newStatus)
    ElMessage.success(`${actionText}成功`)
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 切换热销状态
const handleToggleHot = async (row) => {
  try {
    const newStatus = !row.isHot
    const actionText = newStatus ? '设为热销' : '取消热销'
    
    await ElMessageBox.confirm(`确定要${actionText}该商品吗？`, '提示', {
      type: 'warning'
    })
    
    await updateProductHotStatus(row.id, newStatus)
    ElMessage.success(`${actionText}成功`)
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

// 监听merchantId变化
watch(merchantId, () => {
  if (merchantId.value) {
    fetchProducts()
  }
})

onMounted(() => {
  fetchCategories()
  if (merchantId.value) {
    fetchProducts()
  }
})
</script>

<style scoped>
.product-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button-group .el-button--link {
  padding: 0 8px;
}

.el-button-group .el-button--link:not(:last-child) {
  border-right: 1px solid var(--el-border-color-light);
}
</style>
